package com.icedevcloud.auth.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.icedevcloud.auth.controller.dto.LoginReqDto;
import com.icedevcloud.auth.controller.dto.LoginResDto;
import com.icedevcloud.auth.service.IAuthService;
import com.icedevcloud.common.core.api.Assert;
import com.icedevcloud.common.core.api.ErrorCodeEnum;
import com.icedevcloud.common.core.api.R;
import com.icedevcloud.common.core.exception.ApiException;
import com.icedevcloud.common.security.dto.LoginUserInfoDto;
import com.icedevcloud.common.security.util.SecurityUtil;
import com.icedevcloud.upms.api.user.ISysUserProvider;
import com.icedevcloud.upms.api.user.dto.QueryUserResDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 认证 服务实现类
 * </p>
 *
 * @author dengbing
 * @since 2023-08-12
 */
@RequiredArgsConstructor
@Service
public class AuthServiceImpl implements IAuthService {

    private final ISysUserProvider iSysUserProvider;

    @Override
    public LoginResDto login(LoginReqDto loginReqDto) {

        R<QueryUserResDto> userResDTO = iSysUserProvider.queryUserByUsername(loginReqDto.getUsername());
        Assert.fail(userResDTO.getCode() != R.SUCCESS, ErrorCodeEnum.FAILED.getMessage());
        QueryUserResDto user = userResDTO.getData();

        if (user == null) {
            throw new ApiException(ErrorCodeEnum.USER_OR_PASSWORD_ERROR);
        }

        if (!BCrypt.checkpw(loginReqDto.getPassword(), user.getPassword())) {
            throw new ApiException(ErrorCodeEnum.USER_OR_PASSWORD_ERROR);
        }

        SecurityUtil.login(
                LoginUserInfoDto.builder()
                        .id(user.getId())
                        .username(user.getUsername())
                        .build()
        );

        String tokenValue = StpUtil.getTokenValue();

        LoginResDto resDto = new LoginResDto();
        resDto.setUserId(user.getId());
        resDto.setUsername(user.getUsername());
        resDto.setNickname(user.getNickname());
        resDto.setToken(tokenValue);
        return resDto;
    }

    @Override
    public void logout() {
        SecurityUtil.logout();
    }

}
